package com.yh.correct.controller;

import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;


import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.Crawl;
import com.yh.correct.model.JudicialDeptment;
import com.yh.correct.model.Message;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.UserMap;
import com.yh.correct.service.ICorrectedPersonService;
import com.yh.correct.service.IJudicialDeptmentService;
import com.yh.correct.service.IMessageService;
import com.yh.correct.service.IUserMapService;

@Component
@RestController
@RequestMapping("/usermap")
public class UserMapController {
	private static Logger logger = LogManager.getLogger(UserMapController.class);
	private static final long serialVersionUID = 1L;
	@Autowired
	private IUserMapService isermapservice;
	@Autowired
	private ICorrectedPersonService icorrectedperson;
	@Autowired
	private IJudicialDeptmentService judicialDeptmentService;
	@Autowired
	private IMessageService imessageService;
	/**
	 * 天气
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	    
	@RequestMapping("/tianqi")
	// 1.根据城市查询天气
	@ResponseBody
	public String getWeatherInform(String cityName) {
		// 百度天气API
		String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=郑州&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
		StringBuffer strBuf;
		String cs;
		
		try {
			// 通过浏览器直接访问http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ
			// 5slgyqGDENN7Sy7pw29IUvrZ 是我自己申请的一个AK(许可码)，如果访问不了，可以自己去申请一个新的ak
			// 百度ak申请地址：http://lbsyun.baidu.com/apiconsole/key
			// 要访问的地址URL，通过URLEncoder.encode()函数对于中文进行转码
			
			String baiduUrl1 = "http://api.map.baidu.com/telematics/v3/weather?location=" + URLEncoder.encode(cityName, "utf-8")
					+ "&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ";
			if(cityName==""){
				cs=baiduUrl;
			}
			else{cs=baiduUrl1;}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		strBuf = new StringBuffer();

		try {
			URL url = new URL(baiduUrl);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));// 转码。
			String line = null;
			while ((line = reader.readLine()) != null)
				strBuf.append(line + " ");
			reader.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return strBuf.toString();
		
	}
	   
	/**
	 * 异步加载得到所有司法局信息
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/judic")
	public ResultData locats(CorrectedPerson person) throws Exception {
		ResultData rs = new ResultData();
		List<JudicialDeptment> ls = new ArrayList<JudicialDeptment>();
		ls = isermapservice.getJudicialDeptment();
		if (ls.size() > 0) {
			rs.setCode(0);
			rs.setData(ls);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 定时器
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@Scheduled(cron = "0 0/20 * * * ?")
	public void Test1() throws Exception {
		
		// 得到所有矫正人员
		List<CorrectedPerson> correctedPerson = isermapservice.getAllUser();
		for (CorrectedPerson correctedPerson2 : correctedPerson) {
			// 根据矫正人员得到现在位置
			UserMap user = isermapservice.getUser(correctedPerson2);
			logger.debug("第一个人："+correctedPerson2);
			// 根据人员得到范围信息
			List<Crawl> carwl = isermapservice.getAll(correctedPerson2);
			
			List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
			Point2D.Double point = new Point2D.Double(Double.valueOf(user.getLongitude()),
					Double.valueOf(user.getLatitude()));
			for (Crawl crawl : carwl) {
				logger.debug("范围："+carwl);
				pts.add(new Point2D.Double(Double.valueOf(crawl.getLongitude()), Double.valueOf(crawl.getLatitude())));
			}
			// 判断人员是否在范围之内,如果在返回真,反之返回假并发送短信进行提醒,
			Boolean boo = isermapservice.IsPtInPoly(point, pts);
			logger.debug("范围判断:"+boo);
			if (boo == false) {
				HttpClient client = new HttpClient();
				PostMethod method = new PostMethod("http://106.ihuyi.cn/webservice/sms.php?method=Submit");

				client.getParams().setContentCharset("GBK");
				method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=GBK");
				int mobile_code = (int) ((Math.random() * 9 + 1) * 100000);
				String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");
				NameValuePair[] data = { // 提交短信
						new NameValuePair("account", "C63076651"), // 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
						new NameValuePair("password", "0ceab8e1569ff1d53f475964ccfd2d24"), // 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
						// new NameValuePair("password",
						// util.StringUtil.MD5Encode("密码")),
						new NameValuePair("mobile", correctedPerson2.getPhonenum()),
						new NameValuePair("content", content), 
						};
				method.setRequestBody(data);
				try {
					client.executeMethod(method);
					String SubmitResult = method.getResponseBodyAsString();
					// System.out.println(SubmitResult);
					Document doc = DocumentHelper.parseText(SubmitResult);
					Element root = doc.getRootElement();
					String code = root.elementText("code");
					String msg = root.elementText("msg");
					String smsid = root.elementText("smsid");
					logger.debug(code);
					logger.debug(msg);
					logger.debug(smsid);
					if ("2".equals(code)) {
						logger.debug("短信提交成功");
						Message message = new Message();
						message.setContent(content);
						message.setReceiveId(correctedPerson2.getId());
						message.setSendTime(new Date());
						message.setStatus(Integer.valueOf(code));
						int x = imessageService.addMessage(message);
						if (x > 0) {
							logger.debug("短信写入成功");
						}
					}

				} catch (HttpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}

	}

	/**
	 * 异步加载得到指定司法局下面犯人的信息
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/loca")
	public ResultData locat(JudicialDeptment judicialDeptment) throws Exception {
		ResultData rs = new ResultData();
		List<CorrectedPerson> ls = null;
		ls = isermapservice.getJudicialDeptments(judicialDeptment);
		if (ls != null) {
			rs.setCode(0);
			rs.setData(ls);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 根据矫正人员信息得到最后的位置
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/correct")
	public ResultData correct(CorrectedPerson person) throws Exception {
		ResultData rs = new ResultData();
		UserMap user = null;
		List ls = new ArrayList();
		user = isermapservice.getUserss(person);
		ls.add(user);
		if (user != null) {
			rs.setCode(0);
			rs.setData(ls);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 根据矫正人员信息得到现在的位置
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uuser")
	public ResultData corrects(CorrectedPerson person) throws Exception {
		ResultData rs = new ResultData();
		UserMap user = null;
		List ls = new ArrayList();
		user = isermapservice.getUser(person);
		ls.add(user);
		if (user != null) {
			rs.setCode(0);
			rs.setData(ls);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 向数据库插入范围数据
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/puts")
	public ResultData correc(@RequestParam("lng") String lng, @RequestParam("lat") String lat,
			@RequestParam("id") String id) throws Exception {
		ResultData rs = new ResultData();
		logger.debug(lng, lat, id);
		Crawl user = new Crawl();
		// UserMap user=new UserMap();
		user.setLatitude(lat);
		user.setLongitude(lng);
		user.setTimes(new Date());
		user.setPid(Integer.valueOf(id));
		int i = isermapservice.addMap(user);
		// int i=isermapservice.addUserMap(user);
		// System.out.println(i);
		if (i > 0) {
			rs.setCode(0);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}


	/**
	 * 根据矫正人员信息得到轨迹
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getuser")
	public ResultData corre(CorrectedPerson person, String data1, String data2) throws Exception {
		ResultData rs = new ResultData();
		List<UserMap> ls = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("data1", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(data1));
		map.put("data2", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(data2));
		map.put("person", person);
		ls = isermapservice.getUsers(map);
		if (ls != null) {
			rs.setCode(0);
			rs.setData(ls);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 得到矫正人员范围信息
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/poss")
	public ResultData crre(CorrectedPerson person) throws Exception {
		ResultData rs = new ResultData();
		List<Crawl> ls = null;
		ls = isermapservice.getAll(person);
		if (ls != null) {
			rs.setCode(0);
			rs.setData(ls);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 添加定位
	 * 
	 * @param person
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/adduser")
	public ResultData crres(@RequestParam("lng") String lng, @RequestParam("lat") String lat,
			@RequestParam("id") String id) throws Exception {
		String adds = null;
		ResultData rs = new ResultData();
		UserMap user = new UserMap();
		user.setLatitude(lat);
		user.setLongitude(lng);
		user.setPid(Integer.valueOf(id));
		user.setTimes(new Date());

		// 经纬度转成物理位置
		BufferedReader in = null;
		URL tirc = new URL("http://api.map.baidu.com/geocoder?location=" + lat + "," + lng + "&output=json&key="
				+ "E4805d16520de693a3fe707cdc962045");
		try {
			in = new BufferedReader(new InputStreamReader(tirc.openStream(), "UTF-8"));
			String res;
			StringBuilder sb = new StringBuilder("");
			while ((res = in.readLine()) != null) {
				sb.append(res.trim());
			}
			String str = sb.toString();
			ObjectMapper mapper = new ObjectMapper();
			if (StringUtils.isNotEmpty(str)) {
				JsonNode jsonNode = mapper.readTree(str);
				jsonNode.findValue("status").toString();
				JsonNode resultNode = jsonNode.findValue("result");
				JsonNode locationNode = resultNode.findValue("formatted_address");
				adds = locationNode.toString();
				logger.debug(adds);
			}
			user.setAdds(adds);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		int i = isermapservice.addUserMap(user);
		if (i > 0) {
			rs.setCode(0);
			rs.setMessage("成功");
		} else {
			rs.setCode(-1);
			rs.setMessage("失败");
		}
		return rs;
	}

	/**
	 * 电子围墙首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/wallSkip")
	public ModelAndView wallSkip() {
		return new ModelAndView("map/wall");
	}

	/**
	 * 模糊查询电子围墙信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getWall")
	public ResultData getLikeWall(String cname, String times, Integer pageSize, Integer pageNum) {
		Date eDate = new Date();
		try {
			if (times != null && !"".equals(times)) {
				eDate = new SimpleDateFormat("yyyy-MM-dd").parse(times);
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(eDate);
		calendar.add(calendar.DATE, 1);
		eDate = calendar.getTime();
		String time = new SimpleDateFormat("yyyy-MM-dd").format(eDate);
		logger.debug("模糊查询电子围墙信息!" + time);
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("pageSize", pageSize);
		condition.put("pageNum", pageNum);
		condition.put("name", cname);
		condition.put("times", times);
		condition.put("time", time);
		Page page = null;
		try {
			page = isermapservice.getLikeWall(condition);
		} catch (Exception e) {

			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		if (page != null) {
			List<Object> expire = new ArrayList();
			expire.add(page);
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(expire);
		} else {
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		logger.debug("模糊查询电子围墙信息!");
		return rd;
	}

	/**
	 * 电子围墙信息搜索栏下拉框显示
	 * 
	 * @return
	 */
	@RequestMapping(value = "/mSelect")
	public List<Map<String, Object>> mPersonSelect() {
		List<Map<String, Object>> list = null;
		try {
			list = isermapservice.getAllWalls();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 电子定位首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/locats")
	public ModelAndView locats() {
		return new ModelAndView("map/location");
	}

	/**
	 * 轨迹回访首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/tacks")
	public ModelAndView loc() {
		return new ModelAndView("map/track");
	}

	/**
	 * 电子围墙定位跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/dingwei")
	public ModelAndView locat(CorrectedPerson person) throws Exception {
		List<Object> list = isermapservice.getLocation(person);
		return new ModelAndView("map/locat1", "list", list);
	}

	/**
	 * 电子围墙违规跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weigui1")
	public ModelAndView locat1(CorrectedPerson person) throws Exception {
		List<Object> list = isermapservice.getRuleBreak(person);
		return new ModelAndView("map/weigui", "list", list);
	}

	/**
	 * 电子围墙请假跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/qingjia1")
	public ModelAndView locat2(CorrectedPerson person) throws Exception {
		List<Object> list = isermapservice.getLeavePersonnel(person);
		return new ModelAndView("map/qingjia", "list", list);
	}

	/**
	 * 电子围墙短信跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "/duanxin1")
	public ModelAndView locat3(CorrectedPerson person) throws Exception {
		List<Object> list = isermapservice.getLeavePersonnel(person);
		return new ModelAndView("map/duanxin", "list", list);
	}
}
